# -*- coding: utf-8 -*-

import base64
from odoo import models, fields, api, _
from odoo.exceptions import UserError
from odoo.modules.module import get_module_resource

import datetime


class BasicInfo(models.Model):
    _name = 'basic.info'
    _description = '个人基本信息'
    _order = 'personName'
    _rec_name = 'personName'

    _inherit = ['mail.thread', 'mail.activity.mixin', 'resource.mixin', 'image.mixin']

    # @api.model
    # def _default_image(self):
    #     image_path = get_module_resource('basic_info', 'static/src/img', 'default_image.png')
    #     return base64.b64encode(open(image_path, 'rb').read())

    def _compute_phrId(self):
        self.phrId = self.idCard

    phrId = fields.Char(string="健康档案号", required=True, compute='_compute_phrId')
    middleId = fields.Char(string="中间表")
    cardNo = fields.Char(string="卡号")
    personName = fields.Char(string="姓名", related='resource_id.name', store=True, readonly=False, tracking=True)
    active = fields.Boolean('Active', related='resource_id.active', default=True, store=True, readonly=False)
    resource_id = fields.Many2one('resource.resource')
    sexCode = fields.Selection([
        ('0', '男'),
        ('1', '女'),
        ('2', '不男不女')],
        string="性别", default='0')
    idCard = fields.Char(string="证件号码")
    cardType = fields.Selection([
        ('1', '居民身份证'),
        ('2', '士官证'),
        ('3', '学生证'),
        ('4', '驾驶证'),
        ('5', '护照'),
        ('6', '港澳通行证')],
        string="证件类型", default='1')
    cardNum = fields.Char(string="证件编号")
    workPlace = fields.Char(string="工作单位")
    registeredPermanent = fields.Selection([
        ('1', '户籍'),
        ('2', '非户籍')],
        string="常住类型", default='1')
    nation = fields.Selection([
        ('0', '中国'),
        ('1', '外国')],
        string="国籍", default='0')
    rhBloodCode = fields.Selection([
        ('1', '阳性'),
        ('2', '阴性'),
        ('3', '不详')],
        string="RH阴性", default='2')
    educationCode = fields.Selection([
        ('1', '研究生'),
        ('2', '大学本科'),
        ('3', '大学专科和专科学校'),
        ('4', '中等专业学校'),
        ('5', '技工学校'),
        ('6', '高中'),
        ('7', '初中'),
        ('8', '小学'),
        ('9', '文盲或半文盲'),
        ('10', '不详')],
        string="文化程度", default='1')
    workCode = fields.Selection([
        ('1', '国家机关、党群组织、企业、事业单位负责人'),
        ('2', '专业技术人员'),
        ('3', '办事人员和有关人员'),
        ('4', '商业、服务业人员'),
        ('5', '农、林、牧、渔、水利业生产人员'),
        ('6', '生产、运输设备操作人员及有关人员'),
        ('7', '军人'),
        ('8', '不便分类的其它从业人员'),
        ('9', '无职业')],
        string="职业", default='1')
    maritalStatusCode = fields.Selection([
        ('1', '未婚'),
        ('2', '已婚'),
        ('3', '丧偶'),
        ('4', '离婚'),
        ('5', '未说明的婚姻状况')],
        string="婚姻状况", default='1')
    insuranceCode = fields.Selection([
        ('1', '城镇职工基本医疗保险'),
        ('2', '城镇(城乡)居民基本医疗保险'),
        ('3', '新型农村合作医疗'),
        ('4', '贫困救助'),
        ('5', '商业医疗保险'),
        ('6', '全公费'),
        ('7', '全自费'),
        ('8', '其它')],
        string="支付方式", default='1')
    insuranceType = fields.Integer(string="其它的支付")
    masterFlag = fields.Selection([
        ('0', '否'),
        ('1', '是')],
        string="是否户主", default='0')
    familyId = fields.Char(string="所属家庭")
    a_qt1 = fields.Char(string="其他过敏史")
    diseasetext_check_gm = fields.Selection([
        ('0', '无'),
        ('1', '青霉素'),
        ('2', '硫铵')],
        string="药物过敏史", default='0')
    diseasetext_check_fq = fields.Selection([
        ('1', '无'),
        ('2', '高血压'),
        ('3', '糖尿病'),
        ('4', '冠心病'),
        ('5', '慢性阻塞性肺疾病'),
        ('6', '恶性肿瘤'),
        ('7', '脑卒中'),
        ('8', '严重精神障碍'),
        ('9', '结核病'),
        ('10', '肝炎'),
        ('11', '先天畸形')],
        string="家族疾病史-父亲", default='2')
    diseasetextCheckMQ = fields.Selection([
        ('1', '无'),
        ('2', '高血压'),
        ('3', '糖尿病'),
        ('4', '冠心病'),
        ('5', '慢性阻塞性肺疾病'),
        ('6', '恶性肿瘤'),
        ('7', '脑卒中'),
        ('8', '严重精神障碍'),
        ('9', '结核病'),
        ('10', '肝炎'),
        ('11', '先天畸形')],
        string="家族疾病史-母亲", default='3')
    diseasetextCheckXDJM = fields.Selection([
        ('1', '无'),
        ('2', '高血压'),
        ('3', '糖尿病'),
        ('4', '冠心病'),
        ('5', '慢性阻塞性肺疾病'),
        ('6', '恶性肿瘤'),
        ('7', '脑卒中'),
        ('8', '严重精神障碍'),
        ('9', '结核病'),
        ('10', '肝炎'),
        ('11', '先天畸形')],
        string="家族疾病史-兄弟姐妹", default='4')
    diseasetextCheckZN = fields.Selection([
        ('1', '无'),
        ('2', '高血压'),
        ('3', '糖尿病'),
        ('4', '冠心病'),
        ('5', '慢性阻塞性肺疾病'),
        ('6', '恶性肿瘤'),
        ('7', '脑卒中'),
        ('8', '严重精神障碍'),
        ('9', '结核病'),
        ('10', '肝炎'),
        ('11', '先天畸形')],
        string="家族疾病史-子女", default='5')
    diseasetext_check_bl = fields.Selection([
        ('1', '无'),
        ('2', '化学品'),
        ('3', '毒物'),
        ('4', '射线')],
        string="暴露史", default='1')
    diseasetext_radio_jb = fields.Selection([
        ('1', '无'),
        ('2', '有')],
        string="是否有疾病", default='1')
    diseasetext_zyb = fields.Char(string="职业病")
    diseasetext_qtfdcrb = fields.Char(string="其他法定传染病")
    diseasetext_qt = fields.Char(string="其他")
    confirmdate_gxy = fields.Date(string="确诊时间", default=datetime.date.today())
    diseasetext_check_jb = fields.Char(string="疾病")
    birthday = fields.Date(string="出生日期", default=datetime.date.today())
    contact = fields.Char(string="联系人姓名")
    contactPhone = fields.Char(string="联系人电话")
    bloodTypeCode = fields.Selection([
        ('1', 'A型'),
        ('2', 'B型'),
        ('3', 'O型'),
        ('4', 'AB型'),
        ('5', '不详')],
        string="血型", default="1")
    mobileNumber = fields.Char(string="本人电话")
    diseasetextYCBS = fields.Selection([
        ('1', '无'),
        ('2', '有')],
        string="遗传病史", default='1')
    genetic_his_desc = fields.Char(string="遗传病史描述")
    address = fields.Char(string="现住址")
    homePlace = fields.Char(string="户籍地址")
    isAgrRegister = fields.Selection([
        ('0', '否'),
        ('1', '是')],
        string="是否农业户籍", default='1')
    signFlag = fields.Char(string="签约标志")
    recordSource = fields.Integer(string="档案来源")
    incomeSource = fields.Char(string="经济来源")
    nationCode = fields.Selection([
        ('0', '汉族'),
        ('1', '维吾尔族'),
        ('2', '苗族'),
        ('3', '其它少数民族')],
        string="民族", default='0')
    familyAddress = fields.Char(string="家庭住址")
    householder_rel = fields.Integer(string="与户主关系")
    householder_rel_dscr = fields.Char(string="户主关系描述")
    email = fields.Char(string="电子邮箱")
    town_id = fields.Char(string="乡镇")
    town_name = fields.Char(string="乡镇名称")
    village_id = fields.Char(string="村庄")
    village_name = fields.Char(string="村庄名称")
    householder_id = fields.Char(string="户主")
    householder_name = fields.Char(string="户主姓名")
    householder_id_certnum = fields.Char(string="户主身份证号")
    fam_size = fields.Integer(string="家庭人口数")
    fam_struct = fields.Char(string="家庭结构")
    living_cond = fields.Integer(string="居住情况")
    signa = fields.Char(string="本人签字")
    fam_signa = fields.Char(string="家属签字")
    confirm_time = fields.Date(string="确认时间", default=datetime.date.today())
    createDate = fields.Date(string="建档日期", default=datetime.date.today())
    createUser = fields.Char(string="建档人")
    create_org = fields.Char(string="建档单位")
    division_id = fields.Char(string="所属区划")
    org_id = fields.Char(string="所属机构")
    update_time = fields.Date(string="更新时间", default=datetime.date.today())
    update_operator_id = fields.Char(string="更新操作人")
    is_delete = fields.Boolean(string='是否删除')
    mod_state = fields.Selection([
        ('0', '未上传'),
        ('1', '已上传'),
        ('2', '未完善')],
        string="修改状态", default='0')
    diseasetext_ss = fields.Selection([
        ('0', '无'),
        ('1', '有')],
        string="手术", default='0')
    diseasetext_ssms = fields.Char(string="手术描述")
    diseasetext_ws = fields.Selection([
        ('0', '无'),
        ('1', '有')],
        string="外伤", default='0')
    diseasetext_wsms = fields.Char(string="外伤描述")
    diseasetext_sx = fields.Selection([
        ('0', '无'),
        ('1', '有')],
        string="输血", default='0')
    diseasetext_sxms = fields.Char(string="输血描述")
    shhjCheckCFPFSS = fields.Selection([
        ('1', '无'),
        ('2', '油烟机'),
        ('3', '换气扇'),
        ('4', '烟囱')],
        string="厨房排气设施", default='2')
    shhjCheckRLLX = fields.Selection([
        ('1', '液化气'),
        ('2', '煤'),
        ('3', '天然'),
        ('4', '沼气'),
        ('5', '柴火')],
        string="燃料类型", default='1')
    shhjCheckYS = fields.Selection([
        ('1', '自来水'),
        ('2', '经净化过滤的水'),
        ('3', '井水'),
        ('4', '河湖水'),
        ('5', '塘水')],
        string="饮水", default='2')
    shhjCheckCS = fields.Selection([
        ('1', '卫生厕所'),
        ('2', '一格或二格粪池式'),
        ('3', '马桶'),
        ('4', '露天粪坑'),
        ('5', '简易棚厕')],
        string="厕所", default='1')
    shhjCheckQCL = fields.Selection([
        ('1', '无'),
        ('2', '单设'),
        ('3', '室内'),
        ('4', '室外')],
        string="禽畜栏", default='3')
    auto_create = fields.Selection([
        ('0', '否'),
        ('1', '是')],
        string="是否是自动创建", default='0')
    is_death = fields.Selection([
        ('0', '否'),
        ('1', '是')],
        string="是否死亡", default="0")
    deadDate = fields.Date(string="死亡日期", default=datetime.date.today())
    deadReason = fields.Char(string="死亡原因")
    manaDoctorId = fields.Char(string="责任医生")
    spec_pop_class = fields.Selection([
        ('1', '一般人群'),
        ('2', '老年人'),
        ('3', '高血压'),
        ('4', '糖尿病'),
        ('5', '冠心病'),
        ('6', '残疾人'),
        ('7', '脑卒中')],
        string="人群分类", default='3')
    diseasetextCheckCJ = fields.Selection([
        ('0', '无残疾'),
        ('1', '视力残疾'),
        ('2', '听力残疾'),
        ('3', '言语残疾'),
        ('4', '肢体残疾'),
        ('5', '精神残疾'),
        ('6', '其它残疾')],
    string="残疾状况", default='1')

    datasource = fields.Integer(string="数据来源")
    remark = fields.Text(string="档案备注")

    @api.depends('integrity_rate')
    def _compute_integrity_rate(self):
        self.integrity_rate = 0
    integrity_rate = fields.Integer(string="档案完整率", compute="_compute_integrity_rate", store=True)

    def printBarcode(self):
        print("打印成功")

    def create_expense_from_attachments(self, attachment_ids=None, view_type='tree'):
        ''' Create the expenses from files.
         :return: An action redirecting to hr.expense tree/form view.
        '''
        if attachment_ids is None:
            attachment_ids = []
        attachments = self.env['ir.attachment'].browse(attachment_ids)
        if not attachments:
            raise UserError(_("No attachment was provided"))
        expenses = self.env['hr.expense']

        if any(attachment.res_id or attachment.res_model != 'hr.expense' for attachment in attachments):
            raise UserError(_("Invalid attachments!"))

        product = self.env['product.product'].search([('can_be_expensed', '=', True)])
        if product:
            product = product.filtered(lambda p: p.default_code == "EXP_GEN") or product[0]
        else:
            raise UserError(_("You need to have at least one product that can be expensed in your database to proceed!"))

        for attachment in attachments:
            expense = self.env['hr.expense'].create({
                'personName': attachment.name.split('.')[0],
                'unit_amount': 0,
                'product_id': product.id
            })
            expense.message_post(body=_('Uploaded Attachment'))
            attachment.write({
                'res_model': 'hr.expense',
                'res_id': expense.id,
            })
            attachment.register_as_main_attachment()
            expenses += expense
        if len(expenses) == 1:
            return {
                'name': _('Generated Expense'),
                'view_mode': 'form',
                'res_model': 'hr.expense',
                'type': 'ir.actions.act_window',
                'views': [[False, 'form']],
                'res_id': expenses[0].id,
            }
        return {
            'name': _('Generated Expenses'),
            'domain': [('id', 'in', expenses.ids)],
            'res_model': 'hr.expense',
            'type': 'ir.actions.act_window',
            'views': [[False, view_type], [False, "form"]],
        }

    age = fields.Integer(string="年龄", compute='_compute_age')

    def _compute_age(self):
        for record in self:
            currentYear = datetime.date.today().year
            birYear = record.birthday.year
            self.age = currentYear - birYear

    @api.model
    def create(self, vals):
        # vals['name'] = vals.get('personName')
        res = super(BasicInfo, self).create(vals)
        return res
